package com.fh.interceptor;



import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fh.entity.Member;
import com.fh.entity.base.ClientMessenger;
import com.fh.entity.base.MemberInfo;
import com.fh.entity.base.SessionInfo;
import com.fh.service.member.MemberService;
import com.fh.service.system.user.UserService;
import com.fh.util.PageData;




public class ClientAccessInterceptor extends HandlerInterceptorAdapter {

	@Resource(name="memberService")
	private MemberService memberService;

    private static Logger logger = Logger.getLogger(ClientAccessInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	long startTime = System.currentTimeMillis();
        String digitalCertificate = StringUtils.defaultString(request.getParameter("dc"), request.getParameter("hd_dc"));//用户证书
        String terminalId = StringUtils.defaultString(request.getParameter("tid"), request.getParameter("hd_tid"));//设备号
        String timestamp = StringUtils.defaultString(request.getParameter("ts"), request.getParameter("hd_ts"));//时间戳
        String appKey = StringUtils.defaultString(request.getParameter("ak"), request.getParameter("hd_ak"));//应用标识
        String sign = StringUtils.defaultString(request.getParameter("sign"), request.getParameter("hd_sign"));//签名
        String platform = StringUtils.defaultString(request.getParameter("p"), request.getParameter("hd_p"));//客户端平台
        String cityCode = StringUtils.defaultString(request.getParameter("cc"), request.getParameter("hd_cc"));//用户设置的位置
        String location = StringUtils.defaultString(request.getParameter("loc"), request.getParameter("hd_loc"));//定位位置
        String pid = StringUtils.defaultString(request.getParameter("pid"), request.getParameter("hd_pid"));//推送标识
        //String enterpriseCode = StringUtils.defaultString(request.getParameter("ec"), request.getParameter("hd_ec"));
        String chnl = StringUtils.defaultString(request.getParameter("chnl"), request.getParameter("hd_chnl"));//渠道
        String version = StringUtils.defaultString(request.getParameter("v"), request.getParameter("hd_v"));

        logger.error("===================================================");
        logger.error("digitalCertificate=" + digitalCertificate);
        logger.error("terminalId=" + terminalId);
        logger.error("timestamp=" + timestamp);
        logger.error("appKey=" + appKey);
        logger.error("===================================================");

//        if (StringUtils.isEmpty(terminalId)
//                || StringUtils.isEmpty(timestamp)
//                || StringUtils.isEmpty(appKey)
//                || StringUtils.isEmpty(sign)
//                || StringUtils.isEmpty(platform)
//                || StringUtils.isEmpty(version)
//                ) {
//            logger.info("缺少必须参数");
//            return false;
//        }


//        String appSecret = ConfigManager.getVariable("appSecret");

//        Map parameterMap = new TreeMap<String, String[]>(request.getParameterMap());
//        parameterMap.remove("sign");
//        parameterMap.remove("hd_sign");
        //如果参数签名不合法，则终止当前请求
//        if (!Fun.verifySignature(parameterMap, appSecret, sign)) {
//            logger.info("参数签名校验失败");
//            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
//            return false;
//        }


        String sessionid = null;
        MemberInfo memberInfo = null;
        SessionInfo sessionInfo = null;

        if (!StringUtils.isEmpty(digitalCertificate)) {//证书不为空
        	PageData pd = new PageData();
        	pd.put("TOKEN", digitalCertificate);
        	pd = memberService.getMemberByPhoneAndPwd(pd);
        	if (pd == null) {
        		logger.info("用户查找失败");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return false;
			} else {
				memberInfo = new MemberInfo();
                memberInfo.setMid(pd.getString("MEMBER_ID"));
                memberInfo.setDc(digitalCertificate);
			}
        } 
        else {
            logger.info("用户未登录");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return false;
        }

        String[] urlArr = StringUtils.split(request.getRequestURI(), "/");
        ClientMessenger msg = new ClientMessenger();
        msg.setDc(digitalCertificate);
        msg.setModule(urlArr[urlArr.length - 2]);
        msg.setMethod(urlArr[urlArr.length - 1]);
//        msg.setMs(memberInfo.getMs());
        msg.setExt(StringUtils.defaultString(StringUtils.defaultString(request.getParameter("ext"), request.getParameter("hd_ext")), ""));

//        request.setAttribute("SESSION", session);//会话
        request.setAttribute("CLIENT", sessionInfo);//终端
        request.setAttribute("CURRENTUSER", memberInfo);//用户
        request.setAttribute("OUT", msg);//输出
        response.setHeader("Content-Type", "text/plain");
        logger.error("===============客户端拦截器时耗:" + (System.currentTimeMillis() - startTime) + "============== [" + request.getRequestURI() + "?" + joinRequestParameter(request.getParameterMap(), "&") + "]");
        return super.preHandle(request, response, handler);

    }
    
	public static String joinRequestParameter(Map<String, String[]> map, String separator) {
		StringBuilder buffer = new StringBuilder();
		Iterator i$ = map.entrySet().iterator();

		while (i$.hasNext()) {
			Entry entry = (Entry) i$.next();
			buffer.append((String) entry.getKey()).append("=").append(StringUtils.join((Object[]) entry.getValue()))
					.append(separator);
		}

		return buffer.length() > 0 ? buffer.deleteCharAt(buffer.length() - 1).toString() : "";
	}

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {


        //PerformanceMonitor.end();
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

        super.postHandle(request, response, handler, modelAndView);
    }
}
